/*
 * This file (AkSimpleBlend.java) is protected by the GNU GPL licence (v2). 
 * Please read the license.txt attached for further informations. 
 * 
 */

package alkwarel.blenders;

import processing.core.PImage;
import alkwarel.objects.AkArtspace;
import alkwarel.objects.AkBlender;
import artx.utils.AxLog;

/**
 * Performs a simple blend (objects are drawn on top of each other).
 * 
 * @author Xavier Gouchet
 * 
 */
public class AkDefault extends AkBlender {

	/**
	 * Standard Constructor.
	 */
	public AkDefault() {
		super(1, "default");
	}

	/**
	 * @see alkwarel.objects.AkBlender#Merge(alkwarel.objects.AkArtspace,
	 *      processing.core.PImage, processing.core.PImage)
	 */
	public boolean Merge(AkArtspace a, PImage low, PImage high) {
		if ((low == null) || (high == null))
			return false;
		AxLog.Debug("AkSimpleBlend::Merge =>> merging layers");
		// TODO handle cases when the layers have different sizes
		a.background(0);
		for (int i = 0; i < low.width; i++) {
			for (int j = 0; j < low.height; j++) {
				int lowC = low.get(i, j);
				int highC = high.get(i, j);

				float highA = ((float) ((highC >> 24) & 0xff)) / 255.0f;
				int highR = (highC >> 16) & 0xff;
				int highG = (highC >> 8) & 0xff;
				int highB = highC & 0xff;
				float lowA = 1.0f - highA;
				int lowR = (lowC >> 16) & 0xff;
				int lowG = (lowC >> 8) & 0xff;
				int lowB = lowC & 0xff;

				int colR = (int) ((lowR * lowA) + (highR * highA));
				int colG = (int) ((lowG * lowA) + (highG * highA));
				int colB = (int) ((lowB * lowA) + (highB * highA));
				a.set(i, j, high.get(i, j));
			}
		}
		return true;
	}

}
